/**
 * Created by hsia on 2017/4/12.
 * 按总时长计费
 */
var totalLengthChargeJs = function(targetObj){
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.init();
    return this;
};

var standardBinfo = function(id, $list) {
    if (id == undefined || !id) {
        this.id = "d-" + new Date().getTime();
    } else {
        this.id = id;
    }
    this.$list = $list;
    return this;
}
standardBinfo.prototype = {
    addToList : function($p) {
        $p.createTr(this.$list.find("tbody"));
    }
}
totalLengthChargeJs.prototype={
    init:function(){
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName:"savechargeInfo",fs:this.savechargeInfo},
            {fName:"cancel",fs:function(){$("#"+tempchargeList.monthChargeDivId).data("kendoWindow").close();}},
            {fName:"createRow",fs:this.createRow},
            {fName:"deleteRow",fs:this.deleteRow}];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        this.loadChargeInfo()
    },
    //保存收费标准信息
    savechargeInfo:function(e){
        var that =  $(e.target).data("that");
        if(validityForm(that.targetObj)){
            var chargeInfo = that.sysUtils.getBindDocJson();
            var url = baseApiPath+"chargeStandard/save?isEdit=" + tempchargeList.isEdit;
            var sendJson=chargeInfo;
            for(var o in chargeInfo){
                if(o.indexOf('_') !=-1){
                    var strArray = o.substring(o.indexOf('_')+1);
                    var name = o.substring(0, o.indexOf('_'));
                    var jsonA = {};
                    jsonA[name] = that.recursionObjectName(strArray,chargeInfo[o]) ;
                    delete chargeInfo[o];
                    var sendJson =$.extend(true,chargeInfo,jsonA);
                }
            }
            var flag = true;
            //封装列表数据
            var jsonD= {chargeStandardInfos:{B:{}}};
            that.targetObj.find("#standard-list > tbody tr").each(function (inx, itm) {
                var cols = $(itm).find("td");
                var bg = $(cols[1]).find("input").val();
                var ed = $(cols[2]).find("input").val();
                var je = $(cols[3]).find("input").val();
                if(bg && ed && je){
                    jsonD.chargeStandardInfos.B["array"+inx] = JSON.stringify({beginTime:bg,endTime:ed,payMoney:je});
                }else{
                    notification({ title:"验证失败",message:"列表项不能留空"},'info');
                    flag = false;
                }

            });
            //合并json对象
            sendJson = $.extend(true,sendJson,jsonD);
            if(!tempchargeList.isEdit){
                sendJson["chargeType"]=1;
                sendJson["chargeParamCode"]='totalLength';
            }
            if(!flag){
                return;
            };
            JsonpAjax(url,JSON.stringify(sendJson),"json",function(result){
                $("#"+tempchargeList.monthChargeDivId).data("kendoWindow").close();
                tempchargeList.findGridData();
            });
        }
    },
    recursionObjectName : function (strArray,val) {
        if (strArray.indexOf('_') == -1){
            var jsonC = {};
            jsonC[strArray]=val;
            return jsonC;
        }
        var name = strArray.substring(0, strArray.indexOf('_'));
        strArray = strArray.substring(strArray.indexOf('_')+1);
        var jsonB = {};
        jsonB[name] = this.recursionObjectName(strArray,val);
        return jsonB;
    },
    loadChargeInfo : function(e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        var cumulativeWay = this.targetObj.find("#cumulativeWay");
        var wayA = Utils.getModelValueByModelKey(BASIS.CUMULATIVE_WAY.CUMULATIVE_WAY_A);
        Utils.createDataDictDropDownList([{div:cumulativeWay,parentModelKey:BASIS.CUMULATIVE_WAY.ROOT,select:wayA}],this);
        var freeOvertimeBiling = this.targetObj.find("#freeOvertimeBiling");
        var biling = Utils.getModelValueByModelKey(BASIS.BOTT_LEVEL_ROOT.BOTT_LEVEL_N);
        Utils.createDataDictDropDownList([{div:freeOvertimeBiling,parentModelKey:BASIS.BOTT_LEVEL_ROOT.ROOT,select:biling}],this);
        var freePreferentialWay = this.targetObj.find("#freePreferentialWay");
        var ferentialWay = Utils.getModelValueByModelKey(BASIS.FREE_PREFERENTIAL_WAY.FREE_PREFERENTIAL_WAY_D);
        Utils.createDataDictDropDownList([{div:freePreferentialWay,parentModelKey:BASIS.FREE_PREFERENTIAL_WAY.ROOT,select:ferentialWay}],this);
        if(null == tempchargeList.editResult) return; //新增啥都不需要做
        this.sysUtils.setVariantBindFieldValue(tempchargeList.editResult);
        that.chargeStandardInfos = tempchargeList.editResult.chargeStandardInfos;
        var arrayinfo = that.chargeStandardInfos.B;
        var l = Object.getOwnPropertyNames(arrayinfo).length;
        if (arrayinfo && l < 1) {
            return;
        }
        for (var i = 0; i < l; i++) {
            var key = "array"+i;
            if(arrayinfo.hasOwnProperty(key)){
                var item = eval('(' + arrayinfo[key] + ')');
                that.createTr(that.targetObj.find("#standard-list > tbody"),i,item);
            }

        }

    },
    createTr : function($tbody, id,item) {
        var _this = this;
        var tr = document.createElement("tr");
        var td_check = document.createElement("td");
        var td_BeginTime = document.createElement("td");
        var td_EndTime = document.createElement("td");
        var td_payMoney = document.createElement("td");

        var checkbox = document.createElement("input");
        checkbox.value = id;
        checkbox.tabindex = -1;
        checkbox.type = "checkbox";
        checkbox.name = "standard_ids";
        td_check.appendChild(checkbox);

        var beginTime = document.createElement("input");
        beginTime.type = "text";
        beginTime.value = item == undefined ? '' : item["beginTime"] == undefined ? '' : item["beginTime"];
        beginTime.placeholder = "点我填写,单位[分钟]";
        beginTime.name = "beginTime";
        beginTime.setAttribute('data-validate','number');
        beginTime.setAttribute('validationMessage','请输入纯数字');
        beginTime.pattern = "^[0-9]*$";
        beginTime.required = true;
        td_BeginTime.appendChild(beginTime);

        var endTime = document.createElement("input");
        endTime.type = "text";
        endTime.value = item == undefined ? '' : item["endTime"] == undefined ? '' : item["endTime"];
        endTime.placeholder = "点我填写,单位[分钟]";
        endTime.name = "endTime";
        endTime.setAttribute('data-validate','number');
        endTime.setAttribute('validationMessage','请输入纯数字');
        endTime.pattern = "^[0-9]*$";
        endTime.required = true;
        td_EndTime.appendChild(endTime);

        var payMoney = document.createElement("input");
        payMoney.type = "text";
        payMoney.value = item == undefined ? '' : item["payMoney"] == undefined ? '' : item["payMoney"];
        payMoney.placeholder = "点我填写金额,单位[元]";
        payMoney.name = "payMoney";
        payMoney.setAttribute('data-validate','number');
        payMoney.setAttribute('validationMessage','请输入有效金额,且最多两位小数点');
        payMoney.pattern = "^([0-9]*)+(.[0-9]{1,2})?$";
        payMoney.required = true;
        td_payMoney.appendChild(payMoney);

        payMoney.addEventListener('keydown', function(e) {
            if (e.keyCode == 9) {
                if ($(this).parents("tr").next().length < 1) {
                    var $_no_input = $(this).parents("tr").find("input[name=beginTime]");
                    var _val = $_no_input.val();
                    if (_val == "" || _val == undefined || !_val) {
                        e.returnValue = false;
                        e.cancel = true;
                        $_no_input.focus();
                        return;
                    }
                    e.returnValue = false;
                    e.cancel = true;
                    new standardBinfo(undefined, totalLengthCharge.targetObj.find("#standard-list")).addToList(_this);
                    totalLengthCharge.targetObj.find("#standard-list tbody tr:last input[name=beginTime]").focus();
                    return;
                }
            }
        });
        tr.appendChild(td_check);
        tr.appendChild(td_BeginTime);
        tr.appendChild(td_EndTime);
        tr.appendChild(td_payMoney);
        $tbody[0].appendChild(tr);
    },
    deleteRow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        _this.targetObj.find("input[name=\"standard_ids\"]:checked").each(function(inx, itm) {
            $(itm).parents("tr").remove();
        });
    },
    createRow : function(e) {
        var _this = this;
        if (!isEmpty(e)) {
            _this = $(e.target).data("that");
        }
        new standardBinfo(undefined, totalLengthCharge.targetObj.find("#standard-list")).addToList(_this);
    }
}